const fs = require('fs');
const ethers = require('ethers');

//依赖ethes.js实现合约abi的操作，简单封装一些常用的helper方法

class ContractUtil {
  constructor(abistr) {
    this.contractAbi = '';

    this.contractAbi = JSON.parse(abistr);
    this.contractAbiStr = abistr;
    this.abiInterface = new ethers.Interface(this.contractAbiStr);
  }

  static loadAbiFile(filename) {
    // 读取 ABI 文件
    const abiFileStr = fs.readFileSync(filename, 'utf8');
    var contractABI = new ContractUtil(abiFileStr);
    return contractABI;
  }

  split_to_sigdata(data) {
    var sig = null;
    var inputs = null;
    var pos = 8;
    if (data.substring(0, 2) == '0x') {
      pos = 10;
    }
    sig = data.substring(0, pos);
    inputs = data.substring(pos);
    return [sig, inputs];
  }

  decode_funcion_sigdata(encodedata) {
    var [sig, func_data] = this.split_to_sigdata(encodedata);
    var decoderesult = this.abiInterface.decodeFunctionData(sig, encodedata);
    var functionabi = this.abiInterface.getFunction(sig);
    return [functionabi.name, decoderesult];
  }
}

module.exports.ContractUtil = ContractUtil;
